const state = {
  items: []
}

const mutations = {
  addItem(state, product) {
    let { id, name, price } = product
    let item = state.items.find(v => v.id === id)
    item ? item.quantity++ : state.items.push({id, name, price, quantity: 1})
  }
}

const getters = {
  totalPrice(state) {
    return state.items.reduce((sum, item) => {
      return sum + item.quantity * item.price
    }, 0)
  }
}

const actions = {
  addProductToCart({ commit, dispatch }, product) {
    commit('addItem', product)
    dispatch('product/decrementInventory', product.id, {root: true})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}